﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VERKProjectHopur16.Models;
using System.Web.Security;
using VERKProjectHopur16.Helpers;

namespace VERKProjectHopur16.Controllers
{
    /// <summary>
    /// Controller for logged user and specialists
    /// </summary>
    [Authorize]
    public class UserController : ParentController
    {
        DataRepository m_rep = new DataRepository();

        public ActionResult Index()
        {
            if (User.IsInRole("Administrators"))
            {
                return RedirectToAction("Index", "Admin");
            }
            Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
            var model = (from item in m_rep.AllUsers()
                         where item.UserId == UserID
                         select item).SingleOrDefault();
            return View(model);
        }

        public ActionResult Question()
        {
            var allQ = from item in m_rep.AllQA()
                       where item.CreatorEmail == Membership.GetUser().Email
                       && item.Active == true
                       select item;

            var allAnsQ = from item in m_rep.AllQA()
                          where item.CreatorEmail == Membership.GetUser().Email
                          && item.Active == true
                          && item.Answered == true
                          select item;

            var allUnAnsQ = from item in m_rep.AllQA()
                            where item.CreatorEmail == Membership.GetUser().Email
                            && item.Active == true
                            && item.Answered == false
                            select item;

            UserQAModel model = new UserQAModel();
            model.allQuestions = allQ;
            model.answeredQuestions = allAnsQ;
            model.UnansweredQuestions = allUnAnsQ;
            return View(model);
        }

        public ActionResult ChildProfile()
        {
            Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
            var model = from item in m_rep.AllChilds()
                        where item.CreatorID == UserID
                        orderby item.Name ascending
                        select item;
            return View(model);
        }

        [HttpGet]
        public ActionResult CreateChild()
        {
            return View(new ChildViewModel());
        }

        [HttpPost]
        public ActionResult CreateChild(ChildViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Child item = new Child();
                item.Name = model.Name;
                item.BirthDate = model.BirthDate;
                item.About = model.About;
                item.Created = DateTime.Now;
                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.CreatorID = UserID;
                UpdateModel(item);
                m_rep.AddChild(item);
                return RedirectToAction("ChildProfile");
            }
            return View(model);
        }

        /// <summary>
        /// Get all pictures to render in timeline for a specified child ID
        /// </summary>
        public ActionResult Timeline(int? id)
        {
            if ( id.HasValue )
            {
                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                var result = from item in m_rep.AllPictures()
                             where item.CreatorID == UserID
                             && item.ChildID == id
                             orderby item.PictureDate
                             select item;
                ViewData["ChildID"] = id;
                return View(result);
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult Upload()
        {
            return View();
        }

        /// <summary>
        /// Function saves the picture info in database
        /// Creates a thumb + full size picture which is saved
        /// in /Content/Images folder.
        /// Size can be costumized.
        /// </summary>
        [HttpPost]
        public ActionResult Upload(PictureModel model, int? id)
        {
            if ( ModelState.IsValid && id.HasValue )
            {
                int realId = id.Value;
                string serverPath = Server.MapPath("~");
                string imagesPath = serverPath + "Content\\Images\\";
                string thumbPath = imagesPath + "Thumb\\";
                string fullPath = imagesPath + "Full\\";
                Picture item = new Picture();
                item.PictureID = model.PictureID;
                item.Name = model.Name;
                item.PictureText = model.PictureText;
                item.PictureDate = model.PictureDate;
                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.CreatorID = UserID;
                item.ChildID = realId;
                UpdateModel(item);
                m_rep.AddPicture(item);
                string fileName = item.PictureID.ToString();
                PictureModel.ResizeAndSave(thumbPath, fileName, model.ImageUploaded.InputStream, 250, true);
                PictureModel.ResizeAndSave(fullPath, fileName, model.ImageUploaded.InputStream, 700, true);
                return View();
            }
            return View(model);
        }

        [Authorize(Roles = "Specialist")]
        public ActionResult PendingQuestion()
        {
            var allUnAnsQ = from item in m_rep.AllQA()
                            where item.Active == true
                            && item.Answered == false
                            select item;

            var medUnAnsQ = from item in m_rep.AllQA()
                            where item.DepartmentID == 2
                            && item.Active == true
                            && item.Answered == false
                            select item;

            var psyUnAnsQ = from item in m_rep.AllQA()
                            where item.DepartmentID == 3
                            && item.Active == true
                            && item.Answered == false
                            select item;

            var socUnAnsQ = from item in m_rep.AllQA()
                            where item.DepartmentID == 4
                            && item.Active == true
                            && item.Answered == false
                            select item;

            SpecialistQAModel model = new SpecialistQAModel();
            model.allDept = allUnAnsQ;
            model.medDept = medUnAnsQ;
            model.psyDept = psyUnAnsQ;
            model.socDept = socUnAnsQ;
            return View(model);
        }

        public ActionResult SingleEvent(int? id)
        {
            if (id.HasValue)
            {
                var event_id = id.Value;
                var result = m_rep.GetEventById(event_id);
                if (result == null)
                {
                    return View("NotFound");
                }
                return View(result);
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult SingleQA(int? id)
        {
            if ( id.HasValue )
            {
                var QA_id = id.Value;
                var result = m_rep.GetQAById(QA_id);
                if ( result == null )
                {
                    return View("NotFound");
                }
                return View(result);
            }
            else
            {
                return View("NotFound");
            }
        }

        [Authorize(Roles = "Specialist")]
        [HttpGet]
        public ActionResult AnswerQA(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = m_rep.GetQAById(realID);

                if ( model == null )
                {
                    return View("NotFound");
                }

                QAAnswerModel item = new QAAnswerModel();
                item.QAID = realID;
                item.Answer = model.Answer;

                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        [Authorize(Roles = "Specialist")]
        [HttpPost, ValidateInput(false)]
        public ActionResult AnswerQA(QAAnswerModel model)
        {
            if ( ModelState.IsValid )
            {
                QA item = new QA();

                item.QAID = model.QAID;
                item.Answer = model.Answer;
                item.Answered = true;
                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.AnswerID = UserID;
                item.InsertDate = DateTime.Now;
                m_rep.UpdateQAAnswer(item);
                this.HttpContext.Cache["LatestQA"] = new CacheUpdate().UpdateCacheQA();
                return RedirectToAction("PendingQuestion");
            }
            else
            {
                return View(model);
            }
        }
    }
}
